package com.arvato.common.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author: smallking
 * 
 * @Descibe:基于ObjectMapper的再次封装
 * 
 * @Date: 2018年4月20日  下午12:23:43
 */
@Component
public class JsonUtil {
	/**
	 * 对象转json字符串
	 * @param obj
	 * @return
	 */
	public String obj2String(Object obj) {
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			String resultStr = objectMapper.writeValueAsString(obj);
			return resultStr;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * json字符串转map
	 * @param sourceStr
	 * @return
	 */
	public Map<String, Object> str2Map(String sourceStr){
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			@SuppressWarnings("unchecked")
			Map<String, Object> map = objectMapper.readValue(sourceStr, Map.class);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * json字符串转list对象 
	 * @param sourceStr
	 * @param clazz
	 * @return 
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public <T> List<T> str2List(String sourceStr, Class<?> clazz) throws Exception{
		List<T> list = new ArrayList<T>();
		ObjectMapper objectMapper = new ObjectMapper();
		List<LinkedHashMap<String, Object>> objectList = (List<LinkedHashMap<String, Object>>)objectMapper.readValue(sourceStr, List.class);
		for(LinkedHashMap<String, Object> map : objectList) {
			Object obj = clazz.newInstance();
			BeanUtils.populate(obj, map);
			list.add((T) obj);
		}
		return list;
	}
	
}
